// stores/eventBusStore.js
// 依托pinia实现 事件订阅功能
//示例
// /*
// Test/Parent.vue
// text/child.vue
// /
import { defineStore } from "pinia";
import { ref } from "vue";

export const EventBusStore = defineStore("eventBus", () => {
  const subscribers = ref({});
  const isModalOpen = ref(false); //共享  模态框状态

  /** 如需要 独立模态框
  const modals = ref({}); // { [modalId]: boolean }

function openModal(id) {
  modals.value[id] = true;
}

function closeModal(id) {
  modals.value[id] = false;
}
*/

  function emitEvent(eventName, payload) {
    if (subscribers.value[eventName]) {
      subscribers.value[eventName].forEach((callback) => callback(payload));
    }
  }

  function subscribe(eventName, callback) {
    if (!subscribers.value[eventName]) {
      subscribers.value[eventName] = [];
    }
    subscribers.value[eventName].push(callback);

    return () => {
      subscribers.value[eventName] = subscribers.value[eventName].filter((cb) => cb !== callback);
    };
  }

  function openModal() {
    isModalOpen.value = true;
  }

  function closeModal() {
    isModalOpen.value = false;
  }

  return {
    isModalOpen,
    emitEvent,
    subscribe,
    openModal,
    closeModal,
  };
});
